package http;

import java.util.HashMap;

/**
 * 地址映射
 *
 * @author 50238
 */
public class RequestMapping {
    /**
     * 地址解析
     * {key:地址,类名}
     */
    private final HashMap<String, String> SERVLET_URL = new HashMap<>(1);

    /**
     * 地址解析
     * {key:地址,实例}
     */
    private final HashMap<String, MyServlet> SERVLETS = new HashMap<>(1);

    {
        //这里提前指定了地址和servlet，等于tomcat解析web.xml
        //这里可以写成注解扫描处理servlet或者解析xml处理，后面有时间写一个吧
        SERVLET_URL.put("/hello", "http.Servlet");
        init();
    }

    /**
     * 初始化
     * 通过反射实例化servlet
     */
    private void init() {
        SERVLET_URL.forEach((k, v) -> {
            try {
                try {
                    SERVLETS.put(k, (MyServlet) Class.forName(v).newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 获取servlet
     *
     * @return
     */
    public void dispatch(Request request, Response response) {
        String url = request.getUrl();
        MyServlet myServlet = SERVLETS.get(url);
        myServlet.analysis(request, response);
    }

}
